package com.ukao.steward.ui.valetRunners.createOrder;


import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ukao.steward.R;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.SearchUserBean;
import com.ukao.steward.bean.addressBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.PickerViewDialog;
import com.ukao.steward.listener.MyTextWatcher;
import com.ukao.steward.listener.OnLocationListener;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.GetJsonDataUtil;
import com.ukao.steward.util.KeyBoardUtil;
import com.ukao.steward.util.L;
import com.ukao.steward.util.LocationUtils;
import com.ukao.steward.util.T;
import com.ukao.steward.util.ThreadUtils;
import com.ukao.steward.widget.ZProgressHUD;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 新建地址
 */
public class BuildAddressldFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.left_phone)
    TextView leftPhone;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.left_name)
    TextView leftName;
    @BindView(R.id.product_name)
    EditText name;
    @BindView(R.id.left_district)
    TextView leftDistrict;
    @BindView(R.id.district)
    TextView district;
    @BindView(R.id.detail_district_left)
    TextView detailDistrictLeft;
    @BindView(R.id.detail_district)
    EditText detailDistrict;
    @BindView(R.id.save_btn)
    Button saveBtn;
    Unbinder unbinder;
    private List<addressBean> provinceCityLists;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    public String latitude = "";
    public String longitude = "";
    private String regionalId;
    private String useId;
    private String useName;
    private OptionsPickerView mProvinceDialog;
    int option1,  option2, option3;
;    private ArrayList<addressBean> options1Items = new ArrayList<addressBean>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private LocationUtils mLocationUtils;
    private  boolean  loadFinish;
    private String strphone;
    private boolean isStop=false;
    public ZProgressHUD progressDialogs;


    public static BuildAddressldFragment newInstance(String useId, String name,String  phone) {
        BuildAddressldFragment fragment = new BuildAddressldFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, useId);
        args.putString(ARG_PARAM2, name);
        args.putString(Constant.ARG_PARAM3, phone);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            useId = getArguments().getString(ARG_PARAM1);
            useName = getArguments().getString(ARG_PARAM2);
            strphone= getArguments().getString(Constant.ARG_PARAM3);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_build_addressld, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initListener();

    }



    @Override
    protected void initView() {

        name.setText(useName);
        phone.setText(strphone);
        setStatusBarTintColor(R.color.normal_blue);
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        title.setText("新建地址");
        mLocationUtils= new LocationUtils(_mActivity, mOnLocationListener);
        progressDialogs=showProgressDialog("定位中...");
        ThreadUtils.runOnBackgroundThread(new Runnable() {


            @Override
            public void run() {

                mLocationUtils.startLocation();

            }
        });

        ThreadUtils.runOnBackgroundThread(new Runnable() {
            @Override
            public void run() {

                getAddressProvinceData(_mActivity);
            }
        });


    }






    private OnLocationListener mOnLocationListener = new OnLocationListener() {


        @Override
        public void OnLocationSucceed(final AMapLocation amapLocation) {
            loadFinish=true;

            if (progressDialogs!=null){
                progressDialogs.dismiss();
            }

            longitude = String.valueOf(amapLocation.getLongitude());
            latitude = String.valueOf(amapLocation.getLatitude());
            final      String strProvince=amapLocation.getProvince().replace("省","");
            final      String strCity=amapLocation.getCity().replace("市","");
            final     String strDistrict=amapLocation.getDistrict();
            regionalId=amapLocation.getAdCode();
            district.setText(strProvince+" "+strCity+" "+strDistrict);
            String address = amapLocation.getAddress();
            try {
                if (!strDistrict.isEmpty()) {
                    String temp = strDistrict.substring(strDistrict.length() - 1, strDistrict.length());
                    int indexOf = address.indexOf(temp);
                    if (indexOf != -1) {
                        String detailAddress = address.substring(indexOf + 1, address.length());
                        detailDistrict.setText(detailAddress);

                    }
                }

            } catch (Exception e) {

            }

//            ThreadUtils.runOnBackgroundThread(new Runnable() {
//                @Override
//                public void run() {
//
//                    for (int i = 0; i < options1Items.size(); i++) {
//                        if (options1Items.get(i).getLabel().equals(strProvince)){
//                            option1=i;
//                        }
//                    }
//                    for (int i = 0; i < options2Items.get(option1).size(); i++) {
//                        String  option2Name=options2Items.get(option1).get(i);
//                        if ( option2Name.equals(strCity)){
//                            option2=i;
//                        }
//                    }
//                    for (int i = 0; i < options3Items.get(option1).get(option2).size(); i++) {
//                        String  option3Name=options3Items.get(option1).get(option2).get(i);
//                        if ( option3Name.equals(strDistrict)){
//                            option3=i;
//                        }
//                    }
//
//                    L.i("option1="+option1+"option2+"+option2+"option3="+option3);
//                }
//            });


        }

        @Override
        public void OnLocationFailure(String error) {

        }
    };

    @Override
    protected void initListener() {
        super.initListener();
        name.addTextChangedListener(mTextWatcher);
        phone.addTextChangedListener(mTextWatcher);
        detailDistrict.addTextChangedListener(mTextWatcher);
        district.addTextChangedListener(mTextWatcher);
    }

    private TextWatcher mTextWatcher = new MyTextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            super.afterTextChanged(s);
            isSaveGo();

        }
    };

    private void isSaveGo() {
        String strphone = getText(phone);
        String strname = getText(name);
        String strdistrict = getText(district);
        String strdetailDistrict = getText(detailDistrict);

        if (strphone.isEmpty() || strname.isEmpty()
                || strdistrict.isEmpty() || strdetailDistrict.isEmpty()) {
            if (saveBtn.isEnabled()) {
                saveBtn.setAlpha(0.5f);
                saveBtn.setEnabled(false);
            }

        } else if (!saveBtn.isEnabled()) {
            saveBtn.setAlpha(1f);
            saveBtn.setEnabled(true);
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        isStop=true;
        if (mLocationUtils!=null)
        mLocationUtils.destroyLocation();
    }

    @OnClick({R.id.back_btn, R.id.save_btn, R.id.district})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.save_btn:

                String strPhone = getText(phone);
                String strName = getText(name);
                String strdistrict = getText(district);
                String strdetailDistrict = getText(detailDistrict);
                HashMap mHashMap = new HashMap<String, String>();
                mHashMap.put("accessToken", SaveParams.getToken());
                mHashMap.put("phone", strPhone);
                mHashMap.put("userId", useId);
                mHashMap.put("name", strName);
                mHashMap.put("regionalDesc", strdistrict);/*省市区描述*/
                mHashMap.put("detail", strdetailDistrict);/*详细地址*/
                if (!CheckUtils.isEmpty(regionalId)) {
                    mHashMap.put("regionalId", regionalId);/*区域id*/
                }
                if (!CheckUtils.isEmpty(latitude)) {
                    mHashMap.put("latitude", latitude);/*精度*/
                }
                if (!CheckUtils.isEmpty(longitude)) {
                    mHashMap.put("longitude", longitude);/*纬度*/
                }
                L.i("mHashMap=" + mHashMap.toString());
                addressAdd(mHashMap);


                break;
            case R.id.district:
                KeyBoardUtil.hideKeyboard(_mActivity);
                ShowCityPickerView();




                break;
        }
    }

    private void ShowCityPickerView() {
        try {
            if (mProvinceDialog == null) {
                mProvinceDialog = PickerViewDialog.getInstance().
                        ShowCityPickerViewDe(_mActivity, getString(R.string.city_selection), mOnOptionsSelectListener,option1,option2,option3);
                mProvinceDialog.setPicker(options1Items, options2Items, options3Items);//三级选择器
                mProvinceDialog.show(district);
            } else {
                mProvinceDialog.show(district);

            }
        }catch (Exception  e){

            mProvinceDialog=null;

        }

    }

    private OptionsPickerView.OnOptionsSelectListener mOnOptionsSelectListener = new OptionsPickerView.OnOptionsSelectListener() {


        @Override
        public void onOptionsSelect(int options1, int options2, int options3, View v) {
            //返回的分别是三个级别的选中位置
            String tx = options1Items.get(options1).getPickerViewText() + " " +
                    options2Items.get(options1).get(options2) + " " +
                    options3Items.get(options1).get(options2).get(options3);
            regionalId = provinceCityLists.get(options1).getChildren().get(options2).getChildren().get(options3).getValue() + "";
            district.setText(tx);
            isSaveGo();


        }
    };

    /**
     * 员工新增用户取件地址
     */
    public void addressAdd(final HashMap mHashMap) {
        showProgressDialog();
        addSubscription(apiStores().addressAdd(Constant.createParameter(mHashMap)),
                new ApiCallback<SearchUserBean.AddressListBean>() {
                    @Override
                    public void onSuccess(SearchUserBean.AddressListBean model) {

                        if (model.getHttpCode() == 200) {

                            Bundle mBundle = new Bundle();
                            mBundle.putParcelable(Constant.ARG_PARAM1, model.getData());
                            setFragmentResult(RESULT_OK, mBundle);
                            finish();
                        } else {

                            T.show(model.getMsg());

                        }

                    }


                    @Override
                    public void onFinish() {

                        dismissProgressDialog();

                    }
                });


    }

    public void getAddressProvinceData(Context _mActivity) {
        String JsonData = new GetJsonDataUtil().getJson(_mActivity, "province.json");
        Gson mGson = new Gson();
        provinceCityLists = mGson.fromJson(JsonData,
                new TypeToken<List<addressBean>>() {
                }.getType());

        options1Items = (ArrayList<addressBean>) provinceCityLists;
        if (  !isAdded())return;
        if (isStop)return;
        for (int i = 0; i < provinceCityLists.size(); i++) {    //遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < provinceCityLists.get(i).getChildren().size(); c++) {  //遍历该省份的所有城市
                String CityName = provinceCityLists.get(i).getChildren().get(c).getLabel();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (provinceCityLists.get(i).getChildren().get(c).getChildren() == null
                        || provinceCityLists.get(i).getChildren().get(c).getChildren().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < provinceCityLists.get(i).getChildren().get(c).getChildren().size(); d++) {//该城市对应地区所有数据
                        String AreaName = provinceCityLists.get(i).getChildren().get(c).getChildren().get(d).getLabel();

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);


        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }
}
